import 'package:animate_do/animate_do.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:sjm_lib/component/component_button_gradient.dart';
import 'package:sjm_lib/utils/utils_router.dart';

class UIUtil {
  /// 单例
  UIUtil._internal();

  static UIUtil get instance => _instance;
  static final UIUtil _instance = UIUtil._internal();

  static log(String? tag, dynamic value) {
    if (kReleaseMode) return;
    final stackTrace = StackTrace.current;
    final lineNumber = stackTrace.toString().split("\n")[1];
    debugPrint("$tag====>  $value********************* $lineNumber");
  }

  static showToast(String msg,
      {AlignmentGeometry? align = const Alignment(0, 0.7),
      Color contentColor = const Color(0xff27293d),
      String icon = '',
      int seconds = 2}) {
    BotToast.showText(
        text: '$icon$msg',
        align: align,
        contentColor: contentColor,
        duration: Duration(seconds: seconds));
  }

  static showCustomLoading(ValueNotifier<int> compressProgress,
      {String title = '无损压缩'}) {
    BotToast.showCustomLoading(
        backButtonBehavior: BackButtonBehavior.ignore,
        toastBuilder: (_) {
          return ValueListenableBuilder(
              valueListenable: compressProgress,
              builder: (context, value, child) {
                return Container(
                  height: 100,
                  width: 100,
                  decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.5),
                      borderRadius: BorderRadius.circular(10)),
                  child: Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        CircularProgressIndicator(
                          color: Theme.of(context).primaryColor,
                        ),
                        const SizedBox(height: 10),
                        Text(
                          '$title$value%',
                          style: const TextStyle(color: Colors.white),
                        ),
                      ],
                    ),
                  ),
                );
              });
        });
  }

  static showToastLoading() {
    return BotToast.showLoading(backButtonBehavior: BackButtonBehavior.ignore);
  }

  static closeToastLoading() {
    return BotToast.closeAllLoading();
  }

  static String? keepTwoDecimalPlaces(num number, int decimalPlaces) {
    String numberStr = number.toString(); // 获取字符串
    if (!numberStr.contains('.')) return number.toString();
    List<dynamic> list = numberStr.split('.');
    return '${list[0]}.${list[1].substring(0, list[1].length > decimalPlaces ? decimalPlaces : list[1].length)}';
  }

// 时间格式化，根据总秒数转换为对应的 hh:mm:ss 格式
  static String constructTime(num seconds,
      {List<String> prefix = const ['时', '分', '秒']}) {
    // int day = seconds ~/ 3600 ~/ 24;
    int hour = seconds ~/ 3600;
    int minute = seconds % 3600 ~/ 60;
    int second = (seconds % 60).toInt();
    if (hour != 0) {
      return '$hour${prefix[0]}$minute${prefix[1]}$second${prefix[2]}';
    } else if (minute != 0) {
      return '$minute${prefix[1]}$second${prefix[2]}';
    } else if (second != 0) {
      return '$second${prefix[2]}';
    } else {
      return '0秒';
    }
  }

  //数字格式化，将 0~9 的时间转换为 00~09
  static String formatTime(int timeNum) {
    return timeNum < 10 ? "0$timeNum" : timeNum.toString();
  }

  // 睡眠
  static Future<void> sleep(int milliseconds) async {
    await Future.delayed(Duration(milliseconds: milliseconds));
  }

  // unix 转年月日/时分秒
  static String formatUnix(int unix, TimeFormat format) {
    String time;
    String year = DateTime.fromMillisecondsSinceEpoch(unix)
        .year
        .toString()
        .padLeft(2, '0');
    String month = DateTime.fromMillisecondsSinceEpoch(unix)
        .month
        .toString()
        .padLeft(2, '0');
    String day = DateTime.fromMillisecondsSinceEpoch(unix)
        .day
        .toString()
        .padLeft(2, '0');
    String hour = DateTime.fromMillisecondsSinceEpoch(unix)
        .hour
        .toString()
        .padLeft(2, '0');
    String minute = DateTime.fromMillisecondsSinceEpoch(unix)
        .minute
        .toString()
        .padLeft(2, '0');
    String second = DateTime.fromMillisecondsSinceEpoch(unix)
        .second
        .toString()
        .padLeft(2, '0');

    if (format == TimeFormat.ymd) {
      time = '$year-$month-$day';
    } else if (format == TimeFormat.hms) {
      time = '$hour:$minute:$second';
    } else if (format == TimeFormat.ymdhms) {
      time = '$year-$month-$day $hour:$minute:$second';
    } else {
      time = '时间格式化错误';
    }
    return time;
  }

  static Future<bool?> showAlertDialog(context,
      {String? title,
        String content = '确认吗？',
        bool showCancel = true,
        Widget? contentWidget,
        Color? themeColor,
        Color? textColor,
        confirmText = '确定'}) async {
    return await showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) => FadeInUp(
          duration: const Duration(milliseconds: 300),
          child: AlertDialog(
              alignment: Alignment.center,
              // icon: Image.asset(AppSource.logo,width: 30,height: 30,),
              title: Center(
                  child: Text(title ?? '温馨提示',
                      style: const TextStyle(fontSize: 18))),
              content: contentWidget ??
                  Text(content, textAlign: TextAlign.center),
              actionsAlignment: MainAxisAlignment.center,
              actions: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    showCancel
                        ? ComponentGradientTextButton(
                      color: (themeColor?.withOpacity(0.2) ?? Theme.of(context).scaffoldBackgroundColor),
                      padding:
                      const EdgeInsets.symmetric(vertical: 9),
                      radius: 8,
                      width: 100,
                      title: '取消',
                      textColor: const Color(0xff353535),
                      onTap: () => UtilsNavigator.pop(context,
                          arguments: false),
                    )
                        : const SizedBox(),
                    const SizedBox(width: 15),
                    ComponentGradientTextButton(
                      padding: const EdgeInsets.symmetric(vertical: 9),
                      color:themeColor,
                      radius: 8,
                      width: 100,
                      title: confirmText,
                      textColor: textColor,
                      onTap: () =>
                          UtilsNavigator.pop(context, arguments: true),
                    ),
                  ],
                ),
              ]),
        ));
  }

  static Future<String?> showEditDialog(
    context, {
    String? title,
    String? defaultValue,
    TextInputType? keyboardType,
    Color? themeColor,
    String? placeholder,
  }) async {
    final TextEditingController controller = TextEditingController();
    controller.text = defaultValue ?? '';
    String confirmValue = '';
    return await showDialog(
        barrierDismissible: false,
        context: context,
        builder: (context) {
          return FadeInUp(
            duration: const Duration(milliseconds: 300),
            child: AlertDialog(
                title: Center(
                    child: Text(title ?? '编辑',
                        style: const TextStyle(fontSize: 18))),
                titleTextStyle:
                    Theme.of(context).dialogTheme.titleTextStyle?.copyWith(
                          fontWeight: FontWeight.bold,
                        ),
                content: SingleChildScrollView(
                  child: SizedBox(
                      // height: 1.sh*0.3,
                      child: TextField(
                    autofocus: false,
                    maxLines: null,
                    controller: controller,
                    keyboardType: keyboardType ?? TextInputType.text,
                    decoration: InputDecoration(
                      hintText: placeholder ?? '请输入',
                      focusedBorder: const UnderlineInputBorder(
                          borderSide: BorderSide(color: Color(0xffcccccc))),
                    ),
                    onChanged: (value) {
                      // onChanged(value);
                      confirmValue = value;
                    },
                  )),
                ),
                scrollable: true,
                actions: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      ComponentGradientTextButton(
                        color: (themeColor?.withOpacity(0.2) ?? Theme.of(context).scaffoldBackgroundColor),
                        padding: const EdgeInsets.symmetric(vertical: 9),
                        radius: 8,
                        width: 100,
                        title: '取消',
                        textColor: const Color(0xff353535),
                        onTap: () =>
                            UtilsNavigator.pop(context, arguments: null),
                      ),
                      const SizedBox(width: 15),
                      ComponentGradientTextButton(
                        color: themeColor,
                        padding: const EdgeInsets.symmetric(vertical: 9),
                        radius: 8,
                        width: 100,
                        title: '确定',
                        onTap: () => UtilsNavigator.pop(context,
                            arguments: confirmValue),
                      ),
                    ],
                  ),
                ]),
          );
        });
  }

  static String getHello(String text) {
    final time = DateTime.now();
    final hour = time.hour;
    if (hour < 6) {
      return "$text起的真早！";
    } else if (hour < 9) {
      return "$text早上好！";
    } else if (hour < 12) {
      return "$text上午好！";
    } else if (hour < 14) {
      return "$text中午好！";
    } else if (hour < 18) {
      return "$text下午好！";
    } else if (hour < 20) {
      return "$text晚上好！";
    } else if (hour < 22) {
      return "$text晚上好！";
    } else {
      return "$text深夜了！";
    }
  }

  /// 修改文件的时候，需要把原文件名的后缀带上
  /// 否则后台识别不了
  static String getFileName(String fileName, String newName) {
    if (fileName.contains(".")) {
      return newName + fileName.substring(fileName.lastIndexOf("."));
    }
    return newName;
  }
}

enum TimeFormat {
  ymd,
  hms,
  ymdhms,
}
